package com.virus.coronavirus.service;

import com.virus.coronavirus.error.SystemCodeEnum;
import com.virus.coronavirus.error.SystemException;
import com.virus.coronavirus.mapper.UserMapper;
import com.virus.coronavirus.model.User;
import com.virus.coronavirus.model.vo.UserEditVO;
import com.virus.coronavirus.model.vo.UserInfoVO;
import com.virus.coronavirus.model.vo.UserVO;
import com.virus.coronavirus.response.ActiveUser;
import com.virus.coronavirus.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author: Bbeginner
 * @Date: 2021/2/4 13:39
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectList(Long id){
        return userMapper.selectByPrimaryKey(id);
    }


    /**
     * 编辑
     * @param id
     * @return
     */
    @Transactional
    @Override
    public UserEditVO edit(Long id) throws SystemException {
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要编辑的用户不存在");
        }
        UserEditVO userEditVO = new UserEditVO();
        BeanUtils.copyProperties(user,userEditVO);
        return userEditVO;
    }


    /**
     * 更新
     * @param id
     * @param userVO
     * @return
     */
    @Transactional
    @Override
    public void update(Long id, UserEditVO userVO) throws SystemException {
        User dbUser = userMapper.selectByPrimaryKey(id);
        if(dbUser==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要更新的用户不存在");
        }
        @NotBlank(message = "用户名不能为空")
        String username = userVO.getUsername();
        Example o = new Example(User.class);
        o.createCriteria().andEqualTo("username",username);
        List<User> users = userMapper.selectByExample(o);
        if(!CollectionUtils.isEmpty(users)){
            if(!users.get(0).getId().equals(id)){
                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该用户名已被占用");
            }
        }
        User user = new User();
        BeanUtils.copyProperties(userVO,user);

        user.setAvatar(user.getAvatar());
        user.setModified_time(new Date());
        user.setId(dbUser.getId());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    @Transactional
    @Override
    public void deleteById(Long id) throws SystemException {
        User user = userMapper.selectByPrimaryKey(id);
//        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();

        if(user==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要删除的用户不存在");
        }

//        if(user.getId().equals(activeUser.getUser().getId())){
//            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"不能删除当前登入用户");
//        }
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 添加用户
     * @param userVO
     */
    @Transactional
    @Override
    public void add(UserVO userVO) throws SystemException {
        @NotBlank(message = "用户名不能为空") String username = userVO.getUsername();
        @NotBlank(message = "手机号不能为空") String phone = userVO.getPhone_number();
        Example o = new Example(User.class);
        o.createCriteria().andEqualTo("username",username);
        int i = userMapper.selectCountByExample(o);
        if(i!=0){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该用户名已被占用");
        }

        Example p = new Example(User.class);
        p.createCriteria().andEqualTo("phone_number",phone);
        int j = userMapper.selectCountByExample(p);
        if(j!=0){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该手机号已经注册");
        }

        User user = new User();
        BeanUtils.copyProperties(userVO,user);


        String salt= UUID.randomUUID().toString().substring(0,32);
        user.setPassword(MD5Utils.md5Encryption(user.getPassword(), salt));

        user.setModified_time(new Date());

        user.setCreate_time(new Date());
        user.setSalt(salt);
       /* user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());//添加的用户默认是普通用户
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());//添加的用户默认启用*/

//        user.setAvatar("http://badidol.com/uploads/images/avatars/201910/24/18_1571921832_HG9E55x9NY.jpg");
        user.setAvatar(user.getAvatar());
        userMapper.insert(user);
    }

    /**
     * 查询用户
     * @param name 用户名
     * @return
     */
    @Override
    public User findUserByName(String name) {
        User t = new User();
        t.setUsername(name);
        return userMapper.selectOne(t);
    }

    @Override
    public User findUserById(Long id) {
        User t = new User();
        t.setId(id);
        return userMapper.selectOne(t);
    }

    @Override
    public User findUserByPhone(String phone) {
        User t = new User();
        t.setPhone_number(phone);
        return userMapper.selectOne(t);
    }


    /*下面的功能暂时不去实现,因为需要出与安全考虑,用token和配置shiro*/

    /**
     * 用户信息
     *
     * @return
     */
    @Override
    public UserInfoVO info() throws SystemException {
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setAvatar(activeUser.getUser().getAvatar());
        userInfoVO.setUsername(activeUser.getUser().getUsername());
        // 菜单
//        userInfoVO.setUrl(activeUser.getUrls());
        userInfoVO.setNickname(activeUser.getUser().getNickname());
        return userInfoVO;
    }

    /**
     * 用户登入
     * @param username
     * @param password
     */
    @Override
    public String login(String username, String password) {
        String token = "Nice";
        User user = findUserByName(username);
        if (user != null) {
            String salt = user.getSalt();
            //秘钥为盐
            String target = MD5Utils.md5Encryption(password, salt);
            String dbPassword = user.getPassword();
            if (!target.equals(dbPassword)){
                return "False";
//                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"PASSWORD_ERROR");
            }
            /*//生成Token
            token = JWTUtils.sign(username, target);
            JWTToken jwtToken = new JWTToken(token);
            try {
                SecurityUtils.getSubject().login(jwtToken);
            } catch (AuthenticationException e) {
                throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,e.getMessage());
            }
        } else {
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"用户不存在");*/
        }
        return token;
    }



    /**
     * 用户列表
     * @param userVO
     * @return
     */
    /*@Override
    public PageVO<UserVO> findUserList(Integer pageNum, Integer pageSize, UserVO userVO) {
        return null;
    }
*/

}